import Vue from 'vue'
import Vuex from 'vuex'
import { IAppState } from './modules/app'
import { IUserState } from './modules/user'
import { ITagsViewState } from './modules/tags-view'
import { IErrorLogState } from './modules/error-log'
import { IPermissionState } from './modules/permission'
import { ISettingsState } from './modules/settings'
import { IOemState } from '@/store/modules/oem'
import { IEmailState } from '@/store/modules/email'
import { ISendEmailSettingsState } from './modules/sendEmailSettings'
import { IRunningEmailTaskState } from './modules/runningEmailTask'
Vue.use(Vuex)

export interface IRootState {
  app: IAppState
  user: IUserState
  tagsView: ITagsViewState
  errorLog: IErrorLogState
  permission: IPermissionState
  settings: ISettingsState
  oem: IOemState
  email: IEmailState
  sendEmailSettings: ISendEmailSettingsState
  runningEmailTask: IRunningEmailTaskState
}

// Declare empty store first, dynamically register all modules later.
const store = new Vuex.Store<IRootState>({})
store.subscribe((mut, state) => {
  if (mut.type === 'SET_RECEIVERS' || mut.type.startsWith('SET_EMAIL_')) {
    localStorage.setItem(
      `email_${state.email.userId}`,
      JSON.stringify(state.email)
    )
  } else if (mut.type === 'CHANGE_SEND_EMAIL_SETTING') {
    localStorage.setItem(
      `sendEmailSettings_${state.sendEmailSettings.userId}`,
      JSON.stringify(state.sendEmailSettings)
    )
  }
})
export default store
